package cn.steel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.steel.domain.entity.Order;
import cn.steel.domain.entity.OrderItem;
import cn.steel.domain.entity.User;
import cn.steel.domain.vo.UserVo;
import cn.steel.mapper.OrderItemMapper;
import cn.steel.mapper.OrderMapper;
import cn.steel.mapper.UserMapper;
import cn.steel.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    @Value("${file.save-dir}")
    private String SAVE_DIR;
    @Value("${file.access-prefix}")
    private String ACCESS_PREFIX;
    private static final long MAX_AVATAR_SIZE = 2 * 1024 * 1024; // 2MB

    private final PasswordEncoder passwordEncoder;
    @Override
    public User getUserById(Long id) {
        User user = userMapper.findUserById(id);
        if (user == null || "ADMIN".equals(user.getRole())) {
            throw new IllegalArgumentException("用户不存在或不可操作管理员");
        }
        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        User user = userMapper.getUserByUsername(username);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        return user;
    }

    @Override
    public Page<UserVo> getUsersPaginated(int page, int size, String search, String role, Integer status) {
        PageHelper.startPage(page, size);
        List<User> users = userMapper.findUsersPaginated(search, role, status);
        List<UserVo> userVos = users.stream().map(u -> {
            UserVo vo = new UserVo();
            BeanUtil.copyProperties(u, vo);
            vo.setStatusText(u.getStatus() == 1 ? "启用" : "禁用");
            return vo;
        }).collect(Collectors.toList());

        Page<UserVo> pageResult = new Page<>();
        BeanUtil.copyProperties(users, pageResult);
        pageResult.addAll(userVos);
        return pageResult;
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        User existing = userMapper.findUserById(user.getId());
        if (existing == null || "ADMIN".equals(existing.getRole())) {
            throw new IllegalArgumentException("用户不存在或不可操作管理员");
        }
        userMapper.updateUser(user);
        log.info("Updated user with id: {}", user.getId());
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        User user = userMapper.findUserById(id);
        if (user == null || "ADMIN".equals(user.getRole())) {
            throw new IllegalArgumentException("用户不存在或不可操作管理员");
        }
        if (user.getStatus() == 1) {
            throw new IllegalArgumentException("只能删除已禁用用户");
        }
        userMapper.deleteUser(id);
        log.info("Deleted user with id: {}", id);
    }

    @Override
    @Transactional
    public void toggleUserStatus(Long id, Integer status) {
        User user = userMapper.findUserById(id);
        if (user == null || "ADMIN".equals(user.getRole())) {
            throw new IllegalArgumentException("用户不存在或不可操作管理员");
        }
        if (status != 0 && status != 1) {
            throw new IllegalArgumentException("无效的状态值");
        }
        user.setStatus(status);
        userMapper.updateUser(user);
        log.info("Toggled user status for id: {}, new status: {}", id, status);
    }

    @Override
    @Transactional
    public void updateUserProfile(User user, MultipartFile avatarFile) {
        User existing = userMapper.findUserById(user.getId());
        if (existing == null || !"BUYER".equals(existing.getRole())) {
            throw new IllegalArgumentException("用户不存在或非买家用户");
        }

// 处理头像上传
        if (avatarFile != null && !avatarFile.isEmpty()) {
            if (avatarFile.getSize() > MAX_AVATAR_SIZE) {
                throw new IllegalArgumentException("头像文件大小超过限制（2MB）");
            }
            String originalFilename = avatarFile.getOriginalFilename();
            String extension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase() : "";
            if (!".jpg,.png".contains(extension)) {
                throw new IllegalArgumentException("头像仅支持 JPG 或 PNG 格式");
            }
            // 删除旧头像
            if (existing.getAvatar() != null) {
                File oldFile = new File(SAVE_DIR + existing.getAvatar().substring(ACCESS_PREFIX.length()));
                if (oldFile.exists()) {
                    oldFile.delete();
                }
            }
            // 保存新头像
            String name = user.getUsername();
            String uniqueFileName = "avatar_" + name + "_" + UUID.randomUUID() + extension; // 使用动态扩展名并添加 UUID
            File dest = new File(SAVE_DIR + uniqueFileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                avatarFile.transferTo(dest);
                user.setAvatar(ACCESS_PREFIX + uniqueFileName);
            } catch (IOException e) {
                throw new RuntimeException("头像保存失败", e);
            }
        } else {
            user.setAvatar(existing.getAvatar());
        }

        // 更新用户信息
        user.setPassword(existing.getPassword()); // 防止密码被覆盖
        user.setRole(existing.getRole());
        user.setStatus(existing.getStatus());
        user.setCreateTime(existing.getCreateTime());
        userMapper.updateUser(user);
        log.info("Updated user profile with id: {}", user.getId());
    }

    @Override
    @Transactional
    public void changePassword(Long id, String oldPassword, String newPassword) {
        if (oldPassword == null || oldPassword.isEmpty()){
            throw new IllegalArgumentException("旧密码不能为空");
        }
        if (newPassword == null || newPassword.isEmpty()){
            throw new IllegalArgumentException("新密码不能为空");
        }
        User user = userMapper.findUserById(id);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (!passwordEncoder.matches(oldPassword, user.getPassword())){
            throw new IllegalArgumentException("旧密码错误");
        }
        String encodedNewPassword = passwordEncoder.encode(newPassword);
        user.setPassword(encodedNewPassword);
        userMapper.updateUser(user);
        log.info("Changed password for user with id: {}", id);

    }

    @Override
    public List<User> findUsersByRole(String role) {
        return userMapper.findByRole(role);

    }

    @Override
    public Set<Long> findSuppliersWithOrders(Long buyerId) {
        // 查询该买家的所有订单
        List<Order> orders = orderMapper.findByBuyerId(buyerId);
        if (orders.isEmpty()) {
            return Set.of();
        }
        // 获取订单ID列表
        List<Long> orderIds = orders.stream()
                .map(Order::getId)
                .collect(Collectors.toList());
        // 查询订单项，获取供应商ID
        List<OrderItem> orderItems = orderItemMapper.findByOrderIds(orderIds);
        return orderItems.stream()
                .map(OrderItem::getSupplierId)
                .collect(Collectors.toSet());
    }

    @Override
    public Set<Long> findBuyersWithOrders(Long supplierId) {
        // 查询该供应商的所有订单项
        List<OrderItem> orderItems = orderItemMapper.findBySupplierId(supplierId);
        if (orderItems.isEmpty()) {
            return Set.of();
        }
        // 获取订单ID列表
        List<Long> orderIds = orderItems.stream()
                .map(OrderItem::getOrderId)
                .collect(Collectors.toList());
        // 查询订单，获取买家ID
        List<Order> orders = orderMapper.findByIds(orderIds);
        return orders.stream()
                .map(Order::getBuyerId)
                .collect(Collectors.toSet());
    }
    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

}